<script setup lang="ts">
import { useFilePreview } from '@/composables/useFilePreview'
import { nextTick, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import MarkdownIt from 'markdown-it'
import { renderAsync } from 'docx-preview'
import { downloadFile } from '@/utils/file'
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
})

const props = defineProps<{
  isPreviewOpen: boolean
  file: {
    name?: string
    url?: string
    extension?: string
  } | null
}>()

const emit = defineEmits(['update:isPreviewOpen', 'close'])

const { previewType, markdownContent, getFileType } = useFilePreview()

// 添加 watch 来监听 file 变化
watch(
  () => props.file,
  async (newFile) => {
    if (newFile) {
      // 重新计算 previewType
      previewType.value = getFileType(newFile.extension)

      // 处理 Markdown 文件
      if (newFile.extension === 'md') {
        try {
          const response = await fetch(newFile.url || '')
          const text = await response.text()
          markdownContent.value = md.render(text)
        } catch (error) {
          console.error('Markdown 预览失败:', error)
          Message.error('Markdown 预览失败')
        }
      }
      // 处理 Word 文档
      else if (newFile.extension === 'docx') {
        try {
          // 等待 DOM 更新
          await nextTick()
          const container = document.getElementById('docx-container')
          if (container) {
            container.innerHTML = ''
            const response = await fetch(newFile.url || '')
            const blob = await response.blob()
            await renderAsync(blob, container, container, {
              className: 'docx-viewer',
              inWrapper: true
            })
          }
        } catch (error) {
          console.error('Word 文档预览失败:', error)
          Message.error('Word 文档预览失败')
        }
      }
      // 处理 doc 文件
      else if (newFile.extension === 'doc') {
        Message.warning('暂不支持预览 .doc 格式文件，请下载后查看')
      }
    }
  },
  { immediate: true }
)

const handleClose = () => {
  emit('update:isPreviewOpen', false)
  emit('close')
}
</script>

<template>
  <a-modal
    :visible="isPreviewOpen"
    :title="file?.name"
    @cancel="handleClose"
    @ok="handleClose"
    @update:visible="(val) => emit('update:isPreviewOpen', val)"
    fullscreen
  >
    <!-- Word 文档预览 -->
    <div v-if="previewType === 'office' && file?.extension === 'docx'" class="preview-container">
      <div id="docx-container"></div>
    </div>

    <!-- doc 文件提示 -->
    <div v-else-if="previewType === 'office' && file?.extension === 'doc'" class="preview-container">
      <div class="doc-notice">
        <a-empty>
          <template #image>
            <icon-file style="font-size: 48px; color: var(--color-text-3);" />
          </template>
          <template #description>
            <p>暂不支持预览 .doc 格式文件</p>
            <p>请下载后查看</p>
          </template>
          请下载后查看
        </a-empty>
      </div>
    </div>

    <!-- 图片预览 -->
    <div v-else-if="previewType === 'image'" class="image-preview-container">
      <div class="image-wrapper">
        <a-image :src="file?.url" :alt="file?.name" fit="none" class="preview-image" />
      </div>
    </div>

    <!-- PDF预览 -->
    <div v-else-if="previewType === 'pdf'" class="preview-container">
      <iframe :src="file?.url" frameborder="1" style="overflow: hidden"></iframe>
    </div>

    <!-- Markdown 预览 -->
    <div v-else-if="previewType === 'markdown'" class="markdown-body">
      <div v-html="markdownContent"></div>
    </div>

    <!-- 文本预览 -->
    <div v-else-if="previewType === 'text'" class="preview-container">
      <iframe :src="file?.url" frameborder="0"></iframe>
    </div>
  </a-modal>
</template>

<style scoped>
.preview-container {
  width: 100%;
  height: calc(100vh - 120px);
  overflow: auto;
  background: white;
}

.preview-container iframe {
  width: 100%;
  height: 100%;
  border: none;
}

:deep(.docx-viewer) {
  padding: 20px;
}

.markdown-body {
  padding: 40px;
  max-width: 900px;
  margin: 0 auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.6;
}

/* 添加 docx 预览样式 */
:deep(.docx-viewer) {
  padding: 20px;
  background: white;
}

#docx-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  background: var(--color-fill-2);
}

/* 添加 Markdown 预览样式 */
.markdown-body {
  padding: 40px;
  background: white;
  max-width: 900px;
  margin: 0 auto;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  color: var(--color-text-1);
  line-height: 1.6;
}

.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3),
.markdown-body :deep(h4),
.markdown-body :deep(h5),
.markdown-body :deep(h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body :deep(h1) {
  font-size: 2em;
  padding-bottom: 0.3em;
  border-bottom: 1px solid var(--color-neutral-3);
}

.markdown-body :deep(h2) {
  font-size: 1.5em;
  padding-bottom: 0.3em;
  border-bottom: 1px solid var(--color-neutral-3);
}

.markdown-body :deep(p) {
  margin-bottom: 16px;
}

.markdown-body :deep(a) {
  color: rgb(var(--primary-6));
  text-decoration: none;
}

.markdown-body :deep(a:hover) {
  text-decoration: underline;
}

.markdown-body :deep(code) {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  background-color: var(--color-fill-2);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 85%;
}

.markdown-body :deep(pre) {
  background-color: var(--color-fill-2);
  padding: 16px;
  border-radius: 6px;
  overflow: auto;
  font-size: 85%;
}

.markdown-body :deep(pre code) {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
}

.markdown-body :deep(blockquote) {
  margin: 0 0 16px;
  padding: 0 1em;
  color: var(--color-text-3);
  border-left: 0.25em solid var(--color-neutral-3);
}

.markdown-body :deep(ul),
.markdown-body :deep(ol) {
  padding-left: 2em;
  margin-bottom: 16px;
}

.markdown-body :deep(table) {
  display: block;
  width: 100%;
  overflow: auto;
  margin-bottom: 16px;
  border-spacing: 0;
  border-collapse: collapse;
}

.markdown-body :deep(table th),
.markdown-body :deep(table td) {
  padding: 6px 13px;
  border: 1px solid var(--color-neutral-3);
}

.markdown-body :deep(table tr:nth-child(2n)) {
  background-color: var(--color-fill-2);
}

.markdown-body :deep(img) {
  max-width: 100%;
  box-sizing: content-box;
  background-color: #fff;
}

/* 修改 Markdown 预览样式 */
.markdown-preview {
  padding: 20px;
  background: white;
}

.markdown-preview :deep(.w-e-text-container) {
  height: calc(100vh - 160px) !important;
  background-color: white;
}

.markdown-preview :deep(.w-e-scroll) {
  padding: 0 20px;
}

/* 修改 Markdown 预览样式 */
.markdown-preview {
  padding: 20px;
  background: white;
}

#markdown-preview-container {
  height: calc(100vh - 160px);
  overflow: auto;
}

:deep(.w-e-text-container) {
  background-color: white;
}

:deep(.w-e-scroll) {
  padding: 0 20px;
}

/* 添加图片预览相关样式 */
.image-preview-container {
  width: 100%;
  height: calc(100vh - 120px);
  overflow: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-fill-2);
}

.image-wrapper {
  position: relative;
  display: inline-block;
  max-width: 100%;
  max-height: 100%;
}

:deep(.preview-image) {
  display: block;
  object-fit: none;
  max-width: none;
  max-height: none;
}

/* 确保滚动条样式美观 */
.image-preview-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.image-preview-container::-webkit-scrollbar-track {
  background: var(--color-fill-2);
}

.image-preview-container::-webkit-scrollbar-thumb {
  background: var(--color-fill-4);
  border-radius: 4px;
}

.image-preview-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-fill-5);
}

.doc-notice {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.doc-notice :deep(.arco-empty) {
  padding: 40px;
}
</style>

defineOptions({
  name: 'FilePreview'
})
